package com.heima.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.heima.mapper.NodeMapper;
import com.heima.pojo.dto.NodeQueryDTO;
import com.heima.pojo.entity.TbNode;
import com.heima.pojo.vo.TbSkuPageVO;
import com.heima.pojo.vo.VendingMachineVO;
import com.heima.service.NodeService;
import com.heima.pojo.entity.Business;
import com.heima.pojo.entity.Node;
import com.heima.pojo.vo.NodeVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

@Service
@Slf4j
public class NodeServiceImpl implements NodeService {
    @Autowired
    private NodeMapper nodeMapper;

    @Override
    public TbSkuPageVO search(NodeQueryDTO nodeQueryDTO) {
        PageHelper.startPage(nodeQueryDTO.getPageIndex(), nodeQueryDTO.getPageSize());
        Page<NodeVO> page = nodeMapper.search(nodeQueryDTO);
        TbSkuPageVO tbSkuPageVO = new TbSkuPageVO();
        tbSkuPageVO.setPageIndex((long) page.getPageNum());
        tbSkuPageVO.setPageSize((long) page.getPageSize());
        tbSkuPageVO.setTotalCount(page.getTotal());
        tbSkuPageVO.setTotalPage((long) page.getPages());
        tbSkuPageVO.setCurrentPageRecords(page.getResult());
        return tbSkuPageVO;

    }

    @Override
    public List<Business> searchBusiness() {
        return nodeMapper.searchBusiness();

    }

    @Override
    public Boolean insertBusiness(Node node) {
        return nodeMapper.insertBusiness(node) > 0;

    }

    @Override
    public List<VendingMachineVO> getVmByNodeId(String nodeId) {
        // 调用Mapper查询，MyBatis自动组装分层VO
        List<VendingMachineVO> vmVOList = nodeMapper.selectVmByNodeId(nodeId);

        // 可选：业务逻辑处理（如状态转描述、时间格式化）
        if (vmVOList != null && !vmVOList.isEmpty()) {
            for (VendingMachineVO vmVO : vmVOList) {
                if (vmVO != null && vmVO.getVmStatus() != null) {
                    // 示例：将数字状态转为文字描述（可抽为枚举工具类）
                    String statusDesc = vmVO.getVmStatus() == 1 ? "正常运行" : "异常";
                    // 若需返回状态描述，可在VendingMachineVO中添加vmStatusDesc字段并赋值
                }
            }
        }

        return vmVOList;
    }

    @Override
    public Boolean update(String nodeId, TbNode tbNode) {
        try {
            log.info("开始更新节点，nodeId={}, tbNode={}", nodeId, tbNode);
            // 设置更新时间
            tbNode.setUpdateTime(LocalDateTime.now());
            Boolean result = nodeMapper.updatenode(nodeId, tbNode);
            log.info("节点更新完成，结果: {}", result);
            return result != null ? result : false;
        } catch (Exception e) {
            log.error("更新节点失败，nodeId={}, tbNode={}", nodeId, tbNode, e);
            return false;
        }
    }

    @Override
    public Boolean deleteNode(String nodeId) {
        return nodeMapper.deleteNode(nodeId)>0;
    }

}